<?php

class UsersController  extends Zend_Controller_Action{
    public function init(){

    }

    public function indexAction(){
        $filterUsers = new Application_Form_FilterUser();
        $filterUsers->isValid($this->getRequest()->getParams());

        $usersPaginator = Application_Model_Users::getInstance()
            ->getPaginatorForFilter($filterUsers->getValues());
        $usersPaginator->setItemCountPerPage(12);
        $page = $this->getRequest()->getParam('page');
        if(!is_null($page)){
            $usersPaginator->setCurrentPageNumber($page);
        }
        $this->view->filterUsers = $filterUsers;
        $this->view->filterParams = $this->getRequest()->getParams();
        $this->view->usersPaginator = $usersPaginator;
    }

    public function loginAction(){
        $formLogin = new Application_Form_Login();
        $request = $this->getRequest();
        if($request->isPost()){
            if($formLogin->isValid($request->getPost())){
                $currentUser = Application_Model_Users::getInstance()->login($formLogin->getValues());
                if($currentUser){
                    Zend_Registry::getInstance()->currentUser = $currentUser;
                }
                $this->redirect($this->view->url(array('controller' => 'index', 'action' => 'index'), null, true));
            }
        }
        $this->view->formLogin = $formLogin;
    }

    public function registerEmailAction(){
        $formRegisterEmail = new Application_Form_RegisterEmail();
        $request = $this->getRequest();
        if($request->isPost()){
            if($formRegisterEmail->isValid($request->getPost())){
                Application_Model_Users::getInstance()->createForRegister($formRegisterEmail->getValues());
                $this->redirect($this->view->url(array('controller' => 'users', 'action' => 'login'), null, true));
            }
        }
        $this->view->formRegisterEmail = $formRegisterEmail;
    }

    public function addAction(){
        $formUser = new Application_Form_User();
        $request = $this->getRequest();
        if($request->isPost()){
            if($formUser->isValid($request->getPost())){
                Application_Model_Users::getInstance()->create($formUser->getValues());
                $this->redirect($this->view->url(array('controller' => 'users'), null, true));
            }
        }
        $this->view->formUser = $formUser;
    }
}